<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.proposer"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId">
                  <j-select-depart placeholder="请选择申请部门" v-model="model.departId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep
                    :tdlx="3"
                    placeholder="请选择申请人"
                    :disabled="formDisabled"
                    @back="backUserInfo"
                    v-model="model.employeeId"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart placeholder="请选择申请单位" :disabled="formDisabled" v-model="model.applicant" />
                </a-form-model-item>
              </a-col> -->

              <template v-if="revokedType">
                <a-divider>作废信息</a-divider>
                <a-col :span="8">
                  <a-form-model-item label="单据名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBillId">
                    <SelectPurchaseApplyInput :disabled="formDisabled" v-model="model.purchaseBillId" placeholder="请选择招标采购申请表单" @back="purchaseInfoBack"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationProposer">
                    <select-user-by-dep
                      placeholder="请选择申请人"
                      v-model="model.invalidationProposer"
                      disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationDepartId">
                    <j-select-depart placeholder="请选择申请部门" v-model="model.invalidationDepartId" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationCreateTime">
                    <j-date
                      placeholder="请选择申请时间"
                      v-model="model.invalidationCreateTime"
                      :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                      disabled/>
                  </a-form-model-item>
                </a-col>
              </template>

              <a-col :span="8" v-if="!formDisabled">
                <a-form-model-item label="关联项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <select-project-input projectStatus="2" :proDisabled="true" v-model="model.projectId" placeholder="请选择关联项目" :disabled="formDisabled || revokedType" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-else>
                <a-form-model-item label="关联项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <a-input
                    :readOnly="true"
                    :disabled="!model.projectId_dictText || revokedType"
                    v-model="model.projectId_dictText"
                    style="color: #1890FF;"
                    placeholder="请选择关联项目"
                    @click.prevent="projectClick(model.projectId)"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购总预算（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectBudget">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.projectBudget"
                    placeholder="请输入采购总预算"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input placeholder="请选择团队" :disabled="formDisabled || revokedType" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payManner">
                  <a-input :disabled="formDisabled || revokedType" :max-length="100" v-model="model.payManner" placeholder="请输入付款方式" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="工期(供货期)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplyTime">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择工期"
                    v-model="model.supplyTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="采购大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroadType">
                  <j-dict-select-tag
                    :disabled="formDisabled || revokedType"
                    type="list"
                    v-model="model.provisionBroadType"
                    dictCode="provision_broad_type"
                    placeholder="请选择采购大类"
                    @input="isHideBusinessSegment"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="物料类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
                  <a-select
                    v-model="model.provisionBroad"
                    :disabled="formDisabled || revokedType"
                    placeholder="请选择物料类别"
                    :showSearch="true"
                    :allowClear="true"
                    :filterOption="filterOption"
                    @change="handleChange"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invitationManner">
                  <j-dict-select-tag :disabled="formDisabled || revokedType" type="list" v-model="model.invitationManner" dictCode="bidding_type" placeholder="请选择货到付款" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="showBusinessSegment">
                <a-form-model-item label="所属业务板块" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessSegment">
                  <j-dict-select-tag :disabled="formDisabled || revokedType" type="list" v-model="model.businessSegment" dictCode="business_segment" placeholder="请选择所属业务板块" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="期望到货时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expectUseTime">
                  <j-date
                    :disabled="formDisabled || revokedType"
                    placeholder="请选择到货时间"
                    v-model="model.expectUseTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <!--              上线前完善 4 隐藏主表“项目类型”-->
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item label="项目类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectGenre">-->
              <!--                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.projectGenre" dictCode="purchase_project_type" placeholder="请选择项目类型" />-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <a-col :span="24">
                <a-form-model-item label="采购需求及项目描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="description">
                  <a-input :disabled="formDisabled || revokedType" :max-length="30" v-model="model.description" placeholder="请输入采购需求及项目描述" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled || revokedType" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>

          <!-- 物料明细 -->
          <a-collapse-panel key="2" header="物料明细">
            <a-row :gutter="48">
              <ErpPurchaseApplyInvitationDetailList ref="purchaseApply" :disabled="formDisabled || revokedType" :provisionBroad="model.provisionBroad" @applyDetailData="applyDetailData" />
            </a-row>
          </a-collapse-panel>

          <!-- 附件信息 -->
          <a-collapse-panel key="3" header="附件信息（附件要求：1、业主盖章版合同；2、工程量清单；3、技术要求等）">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!formDisabled || revokedType" :disabled="formDisabled || revokedType" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
        </a-collapse>
        <a-row :gutter="48" v-if="revokedType">
          <a-col :span="24">
            <a-form-model-item label="作废理由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationReason">
              <a-textarea :max-length="500" :disabled="formDisabled" v-model="model.invalidationReason" rows="4" placeholder="请输入作废理由"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <CommonFirstFlowList v-if="model.bpmStatus !== '1'&&formBpm&&revokedType" :formData="OriginalFormData"></CommonFirstFlowList>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>

    <!-- 详情开始 -->
    <erp-project-report-modal ref="projectForm"></erp-project-report-modal>
    <!-- 详情结束 -->
    <ErpPurchaseApplyInvitationFormPrint
      v-if="formBpm"
      class="print_style"
      id="applyinvitationContent"
      :OriginalFormData="OriginalFormData"
      :formData="model"
      :formDataHistory="formData"></ErpPurchaseApplyInvitationFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import ErpPurchaseApplyInvitationDetailList from './reference/ErpPurchaseApplyInvitationDetailList';
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import CommonFirstFlowList from '@/views/components/CommonFirstFlowList.vue';
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import Print from '@/utils/print/printarea.js';
import ErpPurchaseApplyInvitationFormPrint from './ErpPurchaseApplyInvitationFormPrint.vue';
import SelectPurchaseApplyInput from './SelectPurchaseApplyInput'

export default {
    name: 'ErpPurchaseApplyInvitationForm',
    mixins: [viewFile],
    components: {
      ErpProjectReportModal,
      ViewFileModal,
      SelectTeamInput,
      SelectUserByDep,
      ErpPurchaseApplyInvitationDetailList,
      SelectProjectInput,
      CommonFlowList,
      CommonFirstFlowList,
      SelectPurchaseApplyInput,
      ErpPurchaseApplyInvitationFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        userName: '',
        OriginalFormData: {},
        provisionBroadList: [], // 采购大类
        activeKey: ['1', '2', '3'],
        model: {
          checkStatus: 0,
          purchaseBill: null,
          purchaseBillId: null,
          invalidationReason: ''
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          teamId: [
              { required: true, message: '请选择团队!', trigger: 'change' }
          ],
          // 申请人
          // employeeId: [
          //   { required: true, message: '请选择申请人!', trigger: 'change' }
          // ],
          // 申请单位
          // applicant: [
          //   { required: true, message: '请选择申请单位!', trigger: 'change' }
          // ],
          // 申请部门
          // departId: [
          //   { required: true, message: '请选择申请部门!', trigger: 'change' }
          // ],
          // 关联项目 2022年10月17日18:27:18 改为非必填
          // projectId: [
          //   { required: true, message: '请选择关联项目!', trigger: 'change' }
          // ],
          // 项目预算
          projectBudget: [
            { required: true, message: '请输入项目预算!', trigger: 'blur' }
          ],
          // 付款方式
          payManner: [
            { required: true, message: '请输入付款方式!', trigger: 'blur' }
          ],
          // 工期（供货期）
          // supplyTime: [
          //   { required: true, message: '请选择工期!', trigger: 'change' }
          // ],
          // 项目类型 注释原因 上线前完善 4 隐藏主表“项目类型”
          // projectGenre: [
          //   { required: true, message: '请选择项目类型!', trigger: 'blur' }
          // ],
          // 采购方式
          invitationManner: [
            { required: true, message: '请选择采购方式!', trigger: 'blur' }
          ],
          // 期望到货时间
          expectUseTime: [
              { required: true, message: '请选择期望到货时间!', trigger: 'change' }
          ],
          provisionBroad: [
            { required: true, message: '请选择物料类别!', trigger: 'change' }
          ],
          provisionBroadType: [
            { required: true, message: '请选择采购大类!', trigger: 'change' }
          ],
          // 采购需求及项目描述
          description: [
              { required: true, message: '请输入采购需求及项目描述!', trigger: 'blur' }
          ],
          // 所属业务板块
          businessSegment: [
              { required: true, message: '请选择所属业务板块!', trigger: 'blur' }
          ]
        },
        url: {
          add: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/add',
          edit: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/edit',
          queryById: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/queryById',
          queryProvisionBroadList: '/api/erp/purchase/material/erpMaterialCategory/queryAllParent',
          gainBillNo: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/gainBillNo',
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById',
          queryVerification: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/referencedVerification',
          queryVerificationCancelling: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/referencedVerificationCancelling',
          getBizHisProcessNodeInfo: '/api/erpmng/act/process/extActProcessNode/getBizHisProcessNodeInfo'
        },
        details: [],
        provisionBroadups: null,
        showBusinessSegment: false,
        revokedType: false,
        purchaseBillIdBackups: null
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();

      this.findProvisionBroadList()
    },
    methods: {
      ...mapGetters(['userInfo']),
      purchaseInfoBack(item) {
        const that = this
        // 判断不为空
        if (!!this.model.purchaseBillId && item.length > 0) {
          // 判断公司是否变化
          // if(this.purchaseBillIdBackups !== item[0].id)
          getAction(this.url.queryVerification, { id: item[0].id }).then(res => {
            if (res.result == '校验通过') {
              getAction(this.url.queryVerificationCancelling, { id: item[0].id }).then(response => {
                if (response.result == '校验通过') {
                  // 确认后进行改变
                  that.purchaseBillIdBackups = item[0].id
                  that.handleModelData(item[0])
                  that.model.purchaseBillId = item[0].id
                } else {
                  that.$message.warning(response.message)
                  that.model.purchaseBillId = that.purchaseBillIdBackups
                  if (!that.purchaseBillIdBackups) {
                    that.handleModelData()
                  }
                }
              })
            } else {
              that.$message.warning(res.message)
              that.model.purchaseBillId = that.purchaseBillIdBackups
              if (!that.purchaseBillIdBackups) {
                that.handleModelData()
              }
            }
          })
        } else {
          that.handleModelData()
        }
      },
      handleModelData(val) {
        if (val && val.id) {
          // 选择单据 处理原表单数据
          this.$set(this.model, 'invalidationPurchaseBill', val.purchaseBill)
          this.$set(this.model, 'invalidationProposer', val.proposer)
          this.$set(this.model, 'invalidationDepartId', val.departId)
          this.$set(this.model, 'invalidationCreateTime', val.createTime || '')
          this.$set(this.model, 'bpmBizTitle', '作废-' + this.userName + '-' + this.model.purchaseBill)
          this.$set(this.model, 'projectId', val.projectId)
          this.$set(this.model, 'projectBudget', val.projectBudget)
          this.$set(this.model, 'teamId', val.teamId)
          this.$set(this.model, 'payManner', val.payManner)
          this.$set(this.model, 'provisionBroad', val.provisionBroad)
          this.$set(this.model, 'invitationManner', val.invitationManner)
          this.$set(this.model, 'provisionBroadType', val.provisionBroadType)
          this.$set(this.model, 'businessSegment', val.businessSegment)
          this.$set(this.model, 'expectUseTime', val.expectUseTime || '')
          this.$set(this.model, 'description', val.description)
          this.$set(this.model, 'remark', val.remark || '')
          this.$set(this.model, 'purchaseFile', val.purchaseFile || '')
          this.$refs.purchaseApply.loadData(1, val.id)
          if (!!this.model.provisionBroadType && this.model.provisionBroadType == 'administration') {
            // 选择的是行政类
            this.showBusinessSegment = false;
          } else {
            // 选择的不是行政类
            this.showBusinessSegment = true;
          }
        } else {
            // 选择单据 处理原表单数据
          this.$set(this.model, 'invalidationPurchaseBill', '')
          this.$set(this.model, 'invalidationProposer', '')
          this.$set(this.model, 'invalidationDepartId', '')
          this.$set(this.model, 'invalidationCreateTime', '')
          this.$set(this.model, 'projectId', '')
          this.$set(this.model, 'projectBudget', '')
          this.$set(this.model, 'teamId', '')
          this.$set(this.model, 'payManner', '')
          this.$set(this.model, 'provisionBroad', '')
          this.$set(this.model, 'invitationManner', '')
          this.$set(this.model, 'provisionBroadType', '')
          this.$set(this.model, 'businessSegment', '')
          this.$set(this.model, 'expectUseTime', '')
          this.$set(this.model, 'description', '')
          this.$set(this.model, 'remark', '')
          this.$set(this.model, 'purchaseFile', '')
          this.$refs.purchaseApply.dataSource = []
        }
      },
      getBillNo (params = {}) {
        const that = this
        getAction(this.url.gainBillNo, params).then((res) => {
          if (res.success) {
            that.model.purchaseBill = res.result// 单据编号
            if (!that.revokedType) {
              that.model.bpmBizTitle = that.userName + '-' + that.model.purchaseBill// 标题
            } else {
              that.$set(that.model, 'bpmBizTitle', '作废-' + that.userName + '-' + that.model.purchaseBill)
            }
          }
        })
      },
      add (title) {
        this.revokedType = !!title
        if (title) {
          this.$refs['form'].clearValidate();
          this.model = Object.assign({}, {
            purchaseBill: '',
            purchaseBillId: '',
            invalidationReason: ''
          })
          this.purchaseBillIdBackups = null
          this.$refs.purchaseApply.dataSource = []
          this.userName = this.userInfo().empName;// 当前登录人名称
          this.model.proposer = this.userInfo().empId; // 当前登录人
          this.model.departId = this.userInfo().deptId; // 当前登录人部门
          this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
          this.getBillNo({ type: '2' }) // 获取单据编号
          this.validatorRules = {
            purchaseBillId: [
              { required: true, message: '请选择单据名称!', trigger: 'change' }
            ],
            invalidationReason: [
              { required: true, message: '请输入作废理由!', trigger: 'blur' }
            ]
          }
        } else {
          this.edit(this.modelDefault);
          this.userName = this.userInfo().empName;// 当前登录人名称
          this.model.proposer = this.userInfo().empId; // 当前登录人
          this.model.departId = this.userInfo().deptId; // 当前登录人部门
          this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
          this.getBillNo() // 获取单据编号
        }
      },
      edit (record) {
        this.$refs['form'].clearValidate();
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model = Object.assign({}, record);
        this.revokedType = this.model.purchaseBill ? this.model.purchaseBill.substring(0, 2) == 'ZF' : false
        if (this.revokedType) {
          this.validatorRules = {
            purchaseBillId: [
              { required: true, message: '请选择单据名称!', trigger: 'change' }
            ],
            invalidationReason: [
              { required: true, message: '请输入作废理由!', trigger: 'blur' }
            ]
          }
          this.purchaseBillIdBackups = this.model.purchaseBillId
        } else {
          this.validatorRules = {
            teamId: [
              { required: true, message: '请选择团队!', trigger: 'change' }
            ],
            projectBudget: [
              { required: true, message: '请输入项目预算!', trigger: 'blur' }
            ],
            payManner: [
              { required: true, message: '请输入付款方式!', trigger: 'blur' }
            ],
            invitationManner: [
              { required: true, message: '请选择采购方式!', trigger: 'blur' }
            ],
            expectUseTime: [
              { required: true, message: '请选择期望到货时间!', trigger: 'change' }
            ],
            provisionBroad: [
              { required: true, message: '请选择物料类别!', trigger: 'change' }
            ],
            provisionBroadType: [
              { required: true, message: '请选择采购大类!', trigger: 'change' }
            ],
            description: [
              { required: true, message: '请输入采购需求及项目描述!', trigger: 'blur' }
            ],
            businessSegment: [
              { required: true, message: '请选择所属业务板块!', trigger: 'blur' }
            ]
          }
        }
        if (this.model.id) {
          this.$refs.purchaseApply.loadData(1, this.revokedType ? this.model.purchaseBillId : this.model.id)
        } else {
          this.$refs.purchaseApply.dataSource = []
        }
        if (!!this.model.provisionBroadType && this.model.provisionBroadType == 'administration') {
          // 选择的是行政类
          this.showBusinessSegment = false;
        } else {
          // 选择的不是行政类
          this.showBusinessSegment = true;
        }
        this.provisionBroadups = this.model.provisionBroad
        if (this.formBpm === true) {
          getAction(this.url.getBizHisProcessNodeInfo, { flowCode: 'onl_erp_purchase_apply_invitation', dataId: this.model.purchaseBillId }).then((res) => {
            if (res.success) {
              console.log('获取流程节点信息', res);
              var data = {
                dataId: res.result.dataId,
                procInsId: res.result.procInsId,
                tableName: res.result.tableName,
                vars: res.result.records
              }
              this.OriginalFormData = data;
            }
          })
        }
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          let details = this.$refs.purchaseApply.submitForm()
          if (!details.length > 0) {
            this.$message.warning('请添加物料明细信息！');
            this.$emit('unButtonDisable');
            return
          }
          // 判断数据有没有填写数量或者预算价格
          var isAmount = details.some(item => !item.amount);
          var isBudgetAmount = details.some(item => item.budgetAmount === '' || item.budgetAmount === null);
          if (isAmount) {
            // 当为true说明有值领用数量没有填写
            this.$message.warning('请填写物料明细中的数量！');
            this.$emit('unButtonDisable');
            return false
          }
          if (isBudgetAmount) {
            // 当为true说明有值领用用途没有填写
            this.$message.warning('请填写物料明细中的预算价格！');
            this.$emit('unButtonDisable');
            return false
          }
          if (this.model.projectBudget < 10000) {
            this.$message.warning('当前采购总金额小于10000元，请走采购申请单！');
            this.$emit('unButtonDisable');
            return
          }
          if (this.revokedType) {
            getAction(this.url.queryVerification, { id: that.model.purchaseBillId }).then(res => {
              if (res.success) {
                getAction(this.url.queryVerificationCancelling, { id: that.model.purchaseBillId }).then(resp => {
                  if (resp.success) {
                    // 触发表单验证
                    this.$refs.form.validate(valid => {
                      if (valid) {
                        that.submit(type)
                      } else {
                        that.$emit('unButtonDisable')
                      }
                    })
                  } else {
                    that.$message.warning(resp.message);
                    that.$emit('unButtonDisable');
                  }
                })
              } else {
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            })
            return
          }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        let details = this.$refs.purchaseApply.submitForm() || []
        this.model.detailList = details
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 采购大类
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      handleChange(item) {
        // 判断不为空
        if (!!this.model.provisionBroad && !!item) {
          // 判断团队是否变化
          if (this.provisionBroadups !== item) {
            let details = this.$refs.purchaseApply.submitForm()
            if (details.length > 0) {
              const that = this;
              that.$confirm({
                title: '是否确认',
                content: '是否确认切换物料类别，此操作将会清空物料明细中已填写的所有信息？',
                onOk() {
                  // 确认后进行改变
                  that.provisionBroadups = that.model.provisionBroad
                  // 清空子表数据
                  that.$refs.purchaseApply.dataSource = []
                  that.$set(that.model, 'projectBudget', '')
                },
                onCancel() {
                  that.model.provisionBroad = that.provisionBroadups
                }
              });
            } else {
              this.provisionBroadups = item
            }
          }
        }
      },
      isHideBusinessSegment() {
        if (!!this.model.provisionBroadType && this.model.provisionBroadType == 'administration') {
          // 选择的是行政类
          this.showBusinessSegment = false;
        } else {
          // 选择的不是行政类
          this.showBusinessSegment = true;
        }
        // 清空数据
        this.$set(this.model, 'businessSegment', null)
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id': res.id, 'categoryName': res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      applyDetailData(data) {
        this.details = data
        if (this.details.length > 0) {
          let count = 0
          this.details.forEach((item, index) => {
            count = count + (item.amount * item.budgetAmount)
          })
          this.$set(this.model, 'projectBudget', count)
        } else {
          this.$set(this.model, 'projectBudget', '')
        }
      },
      projectClick(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#applyinvitationContent',
          popTitle: '招标采购申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
      // backUserInfo(data) {
      //   this.model.applicant = data[0].orgDepart;//申请人单位
      //   this.model.departId = data[0].departmentId;//申请人部门
      // }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
